package com.atguigu.lease.web.admin.custom.interceptors;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.ThreadLocalUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * projectName: com.atguigu.lease.web.admin.custom.interceptors
 *
 * @author: 赵伟风
 * description:
 * springMvc的拦截器
 *   1. 实现HandlerInterceptor接口
 *   2. 重写拦截方法  [ preHandler ]  postHandler afterCompletion
 *   3. 添加拦截校验
 *       3.1 检查令牌
 *       3.2 有,检查有效期
 *       3.3 放行 return true
 *
 *  4.springmvc的[配置类]或者配置文件声明拦截器
 *       配置拦截的地址  [除了发牌的门,登录的门]
 *       配置放行的地址  [登录的门 (白名单,匿名地址)]
 */
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("access_token");

        if (StringUtils.isBlank(token)){
            //没有牌
            throw  new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        String username = (String) JwtUtil.parseToken(token).get("username");

        ThreadLocalUtils.put(username);

        return true;
    }



}
